package kr.hkit.powerjava.chapter24.dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import kr.hkit.powerjava.chapter24.vo.Department;
import kr.hkit.powerjava.chapter24.vo.Student;

public class DepartmentDAO implements InterfaceDAO<Department>{
	private ArrayList<Department> lists;
	private static final String FILE_NAME = "departmentList.dat";
	@Override
	public void insertItem(Department item) {
		if(!lists.contains(item)) {
			lists.add(item);
		} else {
			System.out.println("같은 학과가 있음");
		}
	}
	@Override
	public void updateItem(Department item) {
		lists.set(lists.indexOf(item), item);
	}
	@Override
	public void deleteItem(Department item) {
		lists.remove(item);
	}
	@Override
	public Department searchItem(Department item) {
		return lists.get(lists.indexOf(item));
	}
	@Override
	public void prnListItem(Comparator<Department> comp) {
		if(comp == null) {
			Collections.sort(lists);
		} else {
			Collections.sort(lists, comp);
		}
		
		for(Department dept : lists) {
			System.out.println("\n" + dept);
		}
		
	}
	@Override
	public void loadFile() {
		ObjectInputStream ois = null;
		
		try {
			ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(FILE_NAME)));
			lists = (ArrayList<Department>) ois.readObject();
		} catch (FileNotFoundException e) {
			try {
				new File(FILE_NAME).createNewFile();
				lists = new ArrayList<>();
			} catch (IOException e1) {}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(ois != null) try { ois.close(); } catch(Exception e) {}
		}
	}
	@Override
	public void saveFile() {
		ObjectOutputStream oos = null;
		try {
			oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
			oos.writeObject(lists);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(oos != null) try { oos.close(); } catch(Exception e) {}
		}
	}
}